package com.itbaizhan.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.itbaizhan.entity.AccountInfo;
import com.itbaizhan.fegin.Bank2ServiceFeign;
import com.itbaizhan.mapper1.AccountInfoMapper;
import com.itbaizhan.service.IAccountInfoService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import io.seata.core.context.RootContext;
import io.seata.spring.annotation.GlobalTransactional;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;


/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author itbaizhan
 * @since 07-04
 */
@Slf4j
@Service
public class AccountInfoServiceImpl extends ServiceImpl<AccountInfoMapper, AccountInfo> implements IAccountInfoService {

    @Autowired
    Bank2ServiceFeign bank2ServiceFeign;
    /**
     * 张三减小金额
     * @param accountNo 银行卡号
     * @param amount 金额
     */
    @GlobalTransactional  //开启全局事务，只在service发起的加上就行
    @Transactional(rollbackFor = Exception.class)  //本地事务，每一个service都要加上这注解
    @Override
    public void updateAccountBalance(String accountNo, Double amount) {

        log.info("********** bank1 张三 XID:{}", RootContext.getXID());
        //1,根据银行卡号查询账号信息
        LambdaQueryWrapper<AccountInfo> queryWrapper = new LambdaQueryWrapper();
        queryWrapper.eq(AccountInfo::getAccountNo,accountNo);
        AccountInfo accountInfo = baseMapper.selectOne(queryWrapper);
        //判断账号是否为空
        if(accountInfo != null){
            accountInfo.setAccountBalance(accountInfo.getAccountBalance() - amount);
            baseMapper.updateById(accountInfo);

            //远程调用bank2，李四账户增加
            bank2ServiceFeign.transfer("2",amount);
            System.out.println(10/0);
        }
    }
}
/*将@GlobalTransactional注解标注在全局事务发起的Service实现方法上，
开启全局事务 ：GlobalTransactionalInterceptor会拦截@GlobalTransactional注解的方法，
生成全局事务ID（XID），XID会在整个分布式事务中传递。
在远程调用时，spring-cloud-alibaba-seata会拦截Feign调用将XID传递到下游服务。*/